#include "cparserstatemanager.h"

/**
 * addNextStateId - assigns next state to current
 * @param stateId
 * @param nextStateTokenId
 * @param nextStateId
 */
void CParserStateManager::addNextStateId(int stateId, int nextStateTokenId,
    int nextStateId) {

  // Find state with given id
  map<int, map<int, int> >::iterator i = stateIds.find(stateId);

  // If state does not exist, create new and assign next state id to it
  // Otherwise assign next state id to the current
  if (i == stateIds.end()) {
    map<int, int> tmp;
    tmp.insert(make_pair(nextStateTokenId, nextStateId));
    stateIds.insert(make_pair(stateId, tmp));    
  } else {
    i->second.insert(make_pair(nextStateTokenId, nextStateId));
  }
}
//---------------------------------------------------------------------------

/**
 * setFirstStateId - sets default state
 * @param firstStateId
 */
void CParserStateManager::setFirstStateId(int firstStateId) {
  this->firstStateId = firstStateId;
}
//---------------------------------------------------------------------------

/**
 * findNextStateId - finds next state matching given token
 * @param stateId
 * @param nextStateTokenId
 * @return next state for "stateId" matching "nextStateTokenId"
 */
int CParserStateManager::findNextStateId(int stateId, int nextStateTokenId) {

  // Find desired state, if it does not exist, return
  map<int, map<int, int> >::iterator i = stateIds.find(stateId);
  if (i == stateIds.end()) {
    return STATE_NOTFOUND;
  }

  // Find next state according to token id, if it does not exist, return
  map<int, int>::iterator j = i->second.find(nextStateTokenId);
  if (j == i->second.end()) {
    return STATE_NOTFOUND;
  }
  return j->second;
}
//---------------------------------------------------------------------------

/**
 * getNextStateIds - return all states after one given
 * @param stateId
 * @return all states after given "stateId"
 */
map<int, int> CParserStateManager::getNextStateIds(int stateId) const {
  map<int, map<int, int> >::const_iterator i = stateIds.find(stateId);
  return i == stateIds.end() ? map<int, int>() : i->second;
}
//---------------------------------------------------------------------------

/**
 * getFirstStateId - returns default state
 * @return default state
 */
int CParserStateManager::getFirstStateId() const {
  return firstStateId;
}
//---------------------------------------------------------------------------
